package com.mlethe.library.socialtool.core;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.mlethe.library.socialtool.callback.ShareActionListener;
import com.mlethe.library.socialtool.entity.Share;
import com.mlethe.library.socialtool.entity.ShareAudio;
import com.mlethe.library.socialtool.entity.ShareImage;
import com.mlethe.library.socialtool.entity.ShareMiniProgram;
import com.mlethe.library.socialtool.entity.ShareText;
import com.mlethe.library.socialtool.entity.ShareVideo;
import com.mlethe.library.socialtool.entity.ShareWeb;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXMusicObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

/**
 * 微信分享工具类
 *
 * @author Mlethe
 */
public class WechatShare {

    private static ShareActionListener mListener;

    public static void setShareActionListener(ShareActionListener listener) {
        mListener = listener;
    }

    public static ShareActionListener getShareActionListener() {
        return mListener;
    }

    /**
     * 分享文本
     *
     * @param flag  (0：分享到微信好友,1：分享到微信朋友圈,2：分享到收藏)
     * @param share 分享的文本
     */
    public static void share(Wechat wechat, int flag, ShareText share) {
        if (!wechat.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.WECHAT);
                mListener = null;
            }
            return;
        }
        //初始化一个 WXTextObject 对象，填写分享的文本内容
        WXTextObject textObj = new WXTextObject();
        textObj.text = share.getTitle();
        // 用 WXTextObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObj;
        msg.description = share.getTitle();
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = Util.buildTransaction(share.getTransaction());
        req.message = msg;
        if (flag == Share.FLAG_FRIEND) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else if (flag == Share.FLAG_MOMENTS) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        } else if (flag == Share.FLAG_COLLECTION) {
            req.scene = SendMessageToWX.Req.WXSceneFavorite;
        }
        // 调用api接口，发送数据到微信
        wechat.getApi().sendReq(req);
    }

    /**
     * 分享图片
     *
     * @param flag (0：分享到微信好友,1：分享到微信朋友圈,2：分享到收藏)
     */
    public static void share(final Context context, final Wechat wechat, final int flag, final ShareImage share) {
        if (!wechat.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.WECHAT);
                mListener = null;
            }
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                byte[] thumbData = null;
                // 初始化 WXImageObject 和 WXMediaMessage 对象
                WXImageObject imgObj = null;
                if (share.getImageUrl() != null && !"".equals(share.getImageUrl())) {   // 网络图片
                    bitmap = Util.url2bitmap(share.getImageUrl());
                    imgObj = new WXImageObject(bitmap);
                } else if (share.getImagePath() != null && !"".equals(share.getImagePath())) {   // 本地图片
                    bitmap = BitmapFactory.decodeFile(share.getImagePath());
                    imgObj = new WXImageObject();
                    imgObj.setImagePath(share.getImagePath());
                } else if (share.getBitmap() != null) {
                    bitmap = share.getBitmap();
                    imgObj = new WXImageObject(bitmap);
                } else if (share.getImageData() != null) {
                    thumbData = share.getImageData();
                    imgObj = new WXImageObject(thumbData);
                } else if (share.getDrawableId() != 0) {
                    bitmap = BitmapFactory.decodeResource(context.getResources(), share.getDrawableId());
                    imgObj = new WXImageObject(bitmap);
                }
                if (imgObj == null) {
                    return;
                }
                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = imgObj;
                // 设置缩略图
                if (bitmap != null) {
                    Bitmap thumbBmp = Util.bitmapFormat(bitmap);
                    msg.setThumbImage(thumbBmp);
                    thumbBmp.recycle();
                } else if (thumbData != null) {
                    msg.thumbData = thumbData;
                }

                // 构造一个Req
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = Util.buildTransaction(share.getTransaction());
                req.message = msg;
                if (flag == Share.FLAG_FRIEND) {
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                } else if (flag == Share.FLAG_MOMENTS) {
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                } else if (flag == Share.FLAG_COLLECTION) {
                    req.scene = SendMessageToWX.Req.WXSceneFavorite;
                }
                req.userOpenId = share.getOpenid();
                // 调用api接口，发送数据到微信
                wechat.getApi().sendReq(req);
            }
        }).start();
    }

    /**
     * 分享网页
     *
     * @param flag (0：分享到微信好友,1：分享到微信朋友圈,2：分享到收藏)
     */
    public static void share(final Context context, final Wechat wechat, final int flag, final ShareWeb share) {
        if (!wechat.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.WECHAT);
                mListener = null;
            }
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap thumbBmp = null;
                byte[] thumbData = null;
                if (share.getImagePath() != null && !"".equals(share.getImagePath())) {   // 本地图片
                    Bitmap bitmap = BitmapFactory.decodeFile(share.getImagePath());
                    thumbBmp = Util.bitmapFormat(bitmap);
                    if (bitmap != null) {
                        bitmap.recycle();
                    }
                } else if (share.getImageUrl() != null && !"".equals(share.getImageUrl())) {   // 网络图片
                    thumbBmp = Util.bitmapFormat(Util.url2bitmap(share.getImageUrl()));
                } else if (share.getBitmap() != null) {   // 本地图片
                    thumbBmp = Util.bitmapFormat(share.getBitmap());
                } else if (share.getImageData() != null) {
                    thumbData = share.getImageData();
                } else if (share.getDrawableId() != 0) {
                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), share.getDrawableId());
                    thumbBmp = Util.bitmapFormat(bitmap);
                    if (bitmap != null) {
                        bitmap.recycle();
                    }
                }
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = share.getUrl();
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = share.getTitle();
                msg.description = share.getDesc();
                if (thumbBmp != null) {
                    msg.setThumbImage(thumbBmp);
                    thumbBmp.recycle();
                } else if (thumbData != null) {
                    msg.thumbData = thumbData;
                }
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = Util.buildTransaction(share.getTransaction());
                req.message = msg;
                if (flag == Share.FLAG_FRIEND) {
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                } else if (flag == Share.FLAG_MOMENTS) {
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                } else if (flag == Share.FLAG_COLLECTION) {
                    req.scene = SendMessageToWX.Req.WXSceneFavorite;
                }
                req.userOpenId = share.getOpenid();
                wechat.getApi().sendReq(req);
            }
        }).start();
    }

    /**
     * 分享音乐
     *
     * @param flag (0：分享到微信好友,1：分享到微信朋友圈,2：分享到收藏)
     */
    public static void share(final Context context, final Wechat wechat, final int flag, final ShareAudio share) {
        if (!wechat.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.WECHAT);
                mListener = null;
            }
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                byte[] thumbData = null;
                if (share.getImageUrl() != null && !"".equals(share.getImageUrl())) {   // 网络图片
                    bitmap = Util.url2bitmap(share.getImageUrl());
                } else if (share.getImagePath() != null && !"".equals(share.getImagePath())) {   // 本地图片
                    bitmap = BitmapFactory.decodeFile(share.getImagePath());
                } else if (share.getBitmap() != null) {
                    bitmap = share.getBitmap();
                } else if (share.getImageData() != null) {
                    thumbData = share.getImageData();
                } else if (share.getDrawableId() != 0) {
                    bitmap = BitmapFactory.decodeResource(context.getResources(), share.getDrawableId());
                }
                // 初始化一个WXMusicObject，填写url
                WXMusicObject musicObj = new WXMusicObject();
                musicObj.musicUrl = share.getAudioUrl();
                musicObj.musicLowBandUrl = share.getAudioLowBandUrl();
                musicObj.musicDataUrl = share.getAudioDataUrl();
                musicObj.musicLowBandDataUrl = share.getAudioLowBandDataUrl();
                // 用 WXMusicObject 对象初始化一个 WXMediaMessage 对象
                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = musicObj;
                msg.title = share.getTitle();
                msg.description = share.getDesc();
                // 设置音乐缩略图
                if (bitmap != null) {
                    Bitmap thumbBmp = Util.bitmapFormat(bitmap);
                    msg.setThumbImage(thumbBmp);
                    thumbBmp.recycle();
                } else if (thumbData != null) {
                    msg.thumbData = thumbData;
                }
                // 构造一个Req
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = Util.buildTransaction(share.getTransaction());
                req.message = msg;
                if (flag == Share.FLAG_FRIEND) {
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                } else if (flag == Share.FLAG_MOMENTS) {
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                } else if (flag == Share.FLAG_COLLECTION) {
                    req.scene = SendMessageToWX.Req.WXSceneFavorite;
                }
                req.userOpenId = share.getOpenid();
                // 调用api接口，发送数据到微信
                wechat.getApi().sendReq(req);
            }
        }).start();
    }

    /**
     * 分享视频
     *
     * @param flag (0：分享到微信好友,1：分享到微信朋友圈,2：分享到收藏)
     */
    public static void share(final Context context, final Wechat wechat, final int flag, final ShareVideo share) {
        if (!wechat.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.WECHAT);
                mListener = null;
            }
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                byte[] thumbData = null;
                if (share.getImageUrl() != null && !"".equals(share.getImageUrl())) {   // 网络图片
                    bitmap = Util.url2bitmap(share.getImageUrl());
                } else if (share.getImagePath() != null && !"".equals(share.getImagePath())) {   // 本地图片
                    bitmap = BitmapFactory.decodeFile(share.getImagePath());
                } else if (share.getBitmap() != null) {
                    bitmap = share.getBitmap();
                } else if (share.getImageData() != null) {
                    thumbData = share.getImageData();
                } else if (share.getDrawableId() != 0) {
                    bitmap = BitmapFactory.decodeResource(context.getResources(), share.getDrawableId());
                }
                // 初始化一个WXVideoObject，填写url
                WXVideoObject videoObj = new WXVideoObject();
                videoObj.videoUrl = share.getVideoPath();
                videoObj.videoLowBandUrl = share.getVideoLowBandUrl();
                // 用 WXVideoObject 对象初始化一个 WXMediaMessage 对象
                WXMediaMessage msg = new WXMediaMessage(videoObj);
                msg.title = share.getTitle();
                msg.description = share.getDesc();
                if (bitmap != null) {
                    Bitmap thumbBmp = Util.bitmapFormat(bitmap);
                    msg.setThumbImage(thumbBmp);
                    thumbBmp.recycle();
                } else if (thumbData != null) {
                    msg.thumbData = thumbData;
                }
                // 构造一个Req
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = Util.buildTransaction(share.getTransaction());
                req.message = msg;
                if (flag == Share.FLAG_FRIEND) {
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                } else if (flag == Share.FLAG_MOMENTS) {
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                } else if (flag == Share.FLAG_COLLECTION) {
                    req.scene = SendMessageToWX.Req.WXSceneFavorite;
                }
                req.userOpenId = share.getOpenid();
                // 调用api接口，发送数据到微信
                wechat.getApi().sendReq(req);
            }
        }).start();
    }

    /**
     * 分享小程序（目前只支持会话）
     */
    public static void share(final Context context, final Wechat wechat, final ShareMiniProgram share) {
        if (!wechat.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.WECHAT);
                mListener = null;
            }
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                byte[] thumbData = null;
                if (share.getImageUrl() != null && !"".equals(share.getImageUrl())) {   // 网络图片
                    bitmap = Util.url2bitmap(share.getImageUrl());
                } else if (share.getImagePath() != null && !"".equals(share.getImagePath())) {   // 本地图片
                    bitmap = BitmapFactory.decodeFile(share.getImagePath());
                } else if (share.getBitmap() != null) {
                    bitmap = share.getBitmap();
                } else if (share.getImageData() != null) {
                    thumbData = share.getImageData();
                } else if (share.getDrawableId() != 0) {
                    bitmap = BitmapFactory.decodeResource(context.getResources(), share.getDrawableId());
                }
                WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
                miniProgramObj.webpageUrl = share.getWebpageUrl(); // 兼容低版本的网页链接
                // 正式版:0，测试版:1，体验版:2
                if (share.getType() == 0) {
                    miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;
                } else if (share.getType() == 1) {
                    miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPROGRAM_TYPE_TEST;
                } else if (share.getType() == 2) {
                    miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPROGRAM_TYPE_PREVIEW;
                }
                miniProgramObj.userName = share.getUserName();     // 小程序原始id
                miniProgramObj.withShareTicket = share.isWithShareTicket();     // 是否使用带shareTicket的分享
                miniProgramObj.path = share.getPath();            //小程序页面路径
                WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
                msg.title = share.getTitle();                    // 小程序消息title
                msg.description = share.getDesc();               // 小程序消息desc
                if (bitmap != null) {
                    Bitmap thumbBmp = Util.bitmapFormat(bitmap, 500, 500);
                    msg.setThumbImage(thumbBmp);
                    thumbBmp.recycle();
                } else if (thumbData != null) {
                    msg.thumbData = thumbData;
                }
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = Util.buildTransaction(share.getTransaction());
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
                wechat.getApi().sendReq(req);
            }
        }).start();
    }
}
